#!/user/bin/python
# -*- coding: utf-8 -*-
'''
 @Time    : 2018/5/10 20:56
 @File    : manager_service.py
 @desc    :
'''
from commonSpiders.creeper.manager import CRAWLER_PROCESS_MANAGER_DICT_KEY
from commonSpiders.creeper.net.msg import CreeperSuccessMsg, CreeperFailure
from commonSpiders.creeper.service.service_base import ClientBaseService
from commonSpiders.net.extend_context import ContextExtend
from commonSpiders.net.message.socketio_msg import Success, Failure
from commonSpiders.utils.singleton import singleton

CLIENT_CRAWLER_PROCESS_MANAGER_SERVICE_KEY = 'client_crawler_manager_service'


@singleton
@ContextExtend.extend(CLIENT_CRAWLER_PROCESS_MANAGER_SERVICE_KEY)
class ClientCrawlerProcessManagerService(ClientBaseService):

    MANAGER_KEY_PREFIX = 'MANAGER_%s'

    def __init__(self):
        pass

    def register_crawler_manager(self, manager):
        '''
        注册爬虫进程管理器
        :param namespace: socketio命名空间对象
        :return:
        '''
        self.context.setdefault(CRAWLER_PROCESS_MANAGER_DICT_KEY, {})

        if manager:
            self.context[CRAWLER_PROCESS_MANAGER_DICT_KEY].setdefault(manager.guid, manager)
            return CreeperSuccessMsg(manager.guid)
        else:
            return CreeperFailure(manager.guid, error='没有找到爬虫进程管理器')

    def register_success(self, manager):
        '''
        爬虫管理器注册成功
        :param namespace: socketio命名空间
        :return:
        '''
        if manager:
            manager.INIT_CRAWLER_PROCESS_FLAG = True

